from ctypes import windll, c_char_p

import facade
from xjlibrary.our_file_dir import BaseDir


class DiscernCode(object):
    """
    将识别验证码封装成一个类
    """

    def __init__(self, logger, codetype=6300):
        self.path = BaseDir.get_file_dir_absolute(__file__)
        self.dllpath = BaseDir.get_new_path(self.path, "yundamaAPI-x64.dll")
        self.appId = 6249  # 软件ＩＤ，开发者分成必要参数。登录开发者后台【我的软件】获得！
        self.appKey = b'439aa4305465df04545dad067bb31751'  # 软件密钥，开发者分成必要参数。登录开发者后台【我的软件】获得！

        # self.YDMApi = windll.LoadLibrary('yundamaAPI-x64')
        self.YDMApi = windll.LoadLibrary(self.dllpath)
        # 注意这里是普通会员账号，不是开发者账号，注册地址 http://www.yundama.com/index/reg/user
        # 开发者可以联系客服领取免费调试题分
        # self.username = b'xujiang'
        # self.password = b'xujiang1994323'
        self.username = b'office'
        self.password = b'officeHelper$123'
        # 例：1004表示4位字母数字，不同类型收费不同。请准确填写，否则影响识别率。在此查询所有类型 http://www.yundama.com/price.html
        self.codetype = codetype
        # 分配30个字节存放识别结果
        self.result = c_char_p(b"                              ")
        # 验证码文件路径
        # self.filename = jpgpath.encode('utf-8')
        self.logger = logger
        # 识别超时时间 单位：秒
        self.timeout = 60

    def easy_decode_by_path(self, jpgpath):
        self.logger.info("正在开始一键识别{}".format(jpgpath))
        # 一键识别函数，无需调用 YDM_SetAppInfo 和 YDM_Login，适合脚本调用
        captchaId = self.YDMApi.YDM_EasyDecodeByPath(self.username,
                                                     self.password,
                                                     self.appId,
                                                     self.appKey,
                                                     jpgpath,
                                                     self.codetype,
                                                     self.timeout,
                                                     self.result)

        self.logger.info("一键识别：验证码ID：%d，识别结果：%s" % (captchaId, self.result.value))
        if int(captchaId) > 0:
            return True, self.result.value
        else:
            self.logger.error("识别失败 请检查原因")
            return False, ""

    def discern_code(self, jpgpath):
        """
        识别验证码通过云打码
        :return:
        """
        jpgpath = jpgpath.encode('utf-8')
        boolresult, code = self.easy_decode_by_path(jpgpath)
        if boolresult:
            code = code.decode()
            return True, code
        else:
            return False, ""


DiscernCode(facade.get_streamlogger())
